<!--
 * @Description: 黑银通用模式
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-10-20 15:49:58
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="index-page">
    <!-- #ifdef H5 -->
    <!-- <hyDownloadTips v-if="shareCode && !isAlipayClient()" :bottom="'180rpx'" /> -->
    <hyDownloadTips v-if="shareCode" :bottom="'160rpx'" />
    <!-- #endif -->
    <searchBar @on-search="onSearch" />
    <!-- banner1 -->
    <u-swiper
      :list="bannerList"
      height="200"
      mode="rect"
      @click="handleBannerClick($event, bannerList)"
    ></u-swiper>
    <view class="section">
      <view class="tit">线下好店</view>
      <view class="actions">
        <view
          :class="['item', `${item.objectType}`]"
          v-for="item in categoryList.list1"
          :key="item.id"
          @tap="handleClick(item)"
        >
          <image
            class="icon"
            :src="getImgFullPath(item.imageUrl)"
            mode="auto"
          />
          <view>{{ item.name }}</view>
        </view>
      </view>
    </view>
    <view class="section" v-if="categoryList.list2.length">
      <view class="tit">宴会定制</view>
      <view class="actions">
        <view
          class="item"
          :objectType="item.objectType"
          v-for="item in categoryList.list2"
          :key="item.id"
          @tap="handleClick(item)"
        >
          <image
            class="icon"
            :src="getImgFullPath(item.imageUrl)"
            mode="auto"
          />
          <view>{{ item.name }}</view>
        </view>
      </view>
    </view>
    <u-swiper
      v-if="hyType.id != 6"
      style="margin-top: 20rpx"
      :list="bannerList2"
      height="160"
      mode="none"
      interval="3500"
      duration="1000"
      @click="handleBannerClick($event, bannerList2)"
    >
    </u-swiper>

    <view style="height: 23rpx"></view>
    <view class="rec">附近门店</view>
    <C_SHOP :integralsRuleId="hyType.id == 0 ? null : hyType.id" />
    <u-back-top :scroll-top="scrollTop"></u-back-top>

    <!-- <hy-tabbar bgColor="#fff"></hy-tabbar> -->
    <!-- #ifdef MP-WEIXIN -->
    <C_POLICY />
    <!-- #endif -->
  </view>
</template>
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import {
  onReady,
  onShow,
  onLoad,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
  onPullDownRefresh
} from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, moneyApi, powerBankApi, productApi } from '@/api'
import { getImgFullPath } from '@/utils'
import { useUserStore } from '@/store'
import searchBar from '@/components/hy-search-bar/index.vue'
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
import icon_heidou from '@/static/mine_hei_dou.png'
import {
  getQueryObject,
  getQueryVariable,
  isAlipayClient,
  isWeChat,
  parseParams
} from '@/utils/common'
import { sharePathFormat } from '@/common/wechat-share'
import C_SHOP from './c_shop.vue'
import C_POLICY from './c_user_policy.vue'

const userStore = useUserStore()
const { hasLogin, walletList } = storeToRefs(userStore)
const categoryList = reactive({
  list1: [],
  list2: []
})
const bannerList = ref([]) // 轮播图top
const bannerList2 = ref([]) // 轮播图midd
const productList = reactive({
  pageIndex: 1,
  pageSize: 18,
  finished: false,
  list: []
})
const status = ref('loadmore')
const scrollTop = ref(0)
const hyType = ref<any>({})
const advertisingEnum = reactive<any>(baseApi.advertising_enum) //选择的模式传参

onPageScroll((e) => {
  scrollTop.value = e.scrollTop
})

const getBaseDataFn = async (type: any, callback: (arg0: any) => void) => {
  const { data } = await baseApi.getAdvertisingList({
    pageIndex: 1,
    pageSize: 20,
    type
  })
  callback(data)
}

// 黑豆商品列表
const getHeidouProductList = async () => {
  const { data } = await productApi.getShopProductList({
    pageIndex: productList.pageIndex,
    pageSize: productList.pageSize,
    shopId: 225 // 黑银商家
  })
  const { records, current, pages } = data
  productList.list.push(...records)
  if (current < pages) {
    productList.pageIndex += 1
  } else {
    productList.finished = true
  }
}

const toProductDetail = (product: { shopId: any; productId: any }) => {
  const { shopId, productId } = product
  uni.navigateTo({
    url: `/pages/productDetail/index?shopId=${shopId}&productId=${productId}`
  })
}
// 跳转线下店
const toShopDetail = (content: string) => {
  const obj = JSON.parse(content)
  uni.navigateTo({
    url: `/pages/physicalShop/index?shopId=${obj.id}&shopType=${obj.shopType}`
  })
}

// 跳转线下店列表页面
const toPhysicalStoreList = (content: any) => {
  uni.navigateTo({
    url: `/pages/physicalShopList/index?categoryData=${content}`
  })
}

const toHeidouShop = () => {
  uni.navigateTo({
    url: '/packageB/pages/heidouShop/index'
  })
}

const toDevice = () => {}

const toWebview = (url: string) => {
  uni.navigateTo({
    url: `/pages/webview/index?url=${url}`
  })
}
const brandIdList = [1, 2, 5, 10, 13, 19, 41]

const handleClick = (adv: {
  webUrl: any
  objectType: any
  content: string
  objectFunctionType: number
  type: number
}) => {
  console.log(adv, '222222222')
  if (adv.content != '') {
    var brandId = JSON.parse(adv.content).shopBrandId
  }
  //adv.type为3002是花了还有金刚区
  if (adv.type == 3002 && brandIdList.includes(brandId)) {
    uni.navigateTo({
      url: `/pages/bigLife/chooseShop?brandId=${brandId}&mode=1`
    })
  } else if (adv.type == 3002 && brandId == 666) {
    uni.navigateTo({
      url: `/packageF/pages/index/index?mode=1`
    })
  } else {
    //   return
    if (!adv.webUrl) {
      switch (adv.objectType) {
        case 10:
          break
        case 13:
          if (adv.objectFunctionType === 100) {
            toPhysicalStoreList(adv.content)
          } else if (adv.objectFunctionType === 101) {
            toShopDetail(adv.content)
          }
          break
        case 100:
          toDevice()
          break
        default:
          break
      }
    } else {
      const origin = adv.webUrl.split('?')[0]
      const params = getQueryObject(adv.webUrl)
      const url = parseParams(origin, params)
      toWebview(url)
    }
  }
}

const onSearch = () => {
  uni.navigateTo({
    url: '/pages/physicalShopList/index'
  })
}

const moneyInfo = ref([
  {
    money: 0,
    walletRuleId: 6,
    name: '黑豆钱包'
  }
])

moneyInfo.value.forEach((e: any) => {
  e.money = computed(() => {
    const money = walletList.value.find(
      (item: any) => item.walletRuleId === e.walletRuleId
    )?.money
    return money || 0
  })
})

async function getMoney() {
  if (hasLogin.value && !walletList.value.length) {
    const { data } = await moneyApi.walletList({ noPaging: true })
    userStore.syncSetWalletList(data)
  }
}

const handleBannerClick = (i: number, dataList: any[]) => {
  console.log(i, dataList, '所有轮播图')

  const data = dataList[i]
  const { objectType, webUrl, content } = data
  switch (objectType) {
    case 0:
      let ppid
      if (content != '') {
        ppid = JSON.parse(content).shopBrandId
      }
      console.log(ppid, 'ppid444')
      // 跳转大牌
      if (ppid == 1 || ppid == 13) {
        uni.navigateTo({
          url: `/pages/bigLife/chooseShop?brandId=${ppid}&mode=1`
        })
      } else if (ppid == 666) {
        // 跳转电影院
        uni.navigateTo({
          url: `/packageF/pages/index/index?mode=1`
        })
      }
      break
    case 8:
      if (webUrl) {
        const params = getQueryObject(webUrl)
        if (params?.redirect_url) {
          uni.navigateTo({
            url: params.redirect_url,
            fail: (res) => {
              uni.navigateTo({
                url: `/pages/webview/index?url=${webUrl}`
              })
            }
          })
          return
        }
        const origin = webUrl.split('?')[0]
        if (params?.from && params.from.toLowerCase() === 'app') {
          delete params.from
        }
        const url = parseParams(origin, params)
        toWebview(url)
      }
      break
    case 13:
      if (content) {
        const obj = JSON.parse(content)
        uni.navigateTo({
          url: `/pages/physicalShop/index?shopId=${obj.id}&shopType=${obj.shopType}`
        })
      }
      break
    case 10:
      if (content) {
        const obj = JSON.parse(content)
        uni.navigateTo({
          url: `/pages/productDetail/index?shopId=${obj.shopId}&productId=${obj.productId}`
        })
      }
      break
    default:
      break
  }
}

const shareCode = ref()

// 首页加载渲染
const startRendering = async (xxhd: any, bannerTop: any, bannerBottom: any) => {
  // 线下好店
  getBaseDataFn(xxhd, (data) => {
    categoryList.list1 = data.records
  })
  // banner
  getBaseDataFn(bannerTop, (data) => {
    const { records } = data
    records.forEach((element: { image: string }) => {
      element.image = getImgFullPath(element.imageUrl) || ''
    })
    bannerList.value = data.records
  })
  // banner2
  getBaseDataFn(bannerBottom, (data) => {
    const { records } = data
    records.forEach((element: { image: string }) => {
      element.image = getImgFullPath(element.imageUrl) || ''
    })
    bannerList2.value = data.records
  })
}

// 如果切换了模式
const changeMode = () => {
  if (uni.getStorageSync('hyType')) {
    hyType.value = JSON.parse(uni.getStorageSync('hyType'))
    switch (hyType.value.id) {
      case 0: // 黑银模式
        startRendering(
          advertisingEnum.ADV_HOME_LIST2,
          advertisingEnum.ADV_HOME_BANNER1,
          advertisingEnum.ADV_HOME_BANNER2
        )
        break
      case 1: // 花积分模式
        startRendering(
          advertisingEnum.HLHY_XXHD,
          advertisingEnum.HLHY_BANNER1,
          advertisingEnum.HLHY_BANNER2
        )
        break
      case 2: // 链动模式
        startRendering(
          advertisingEnum.BYLD_XXHD,
          advertisingEnum.ADV_HOME_BANNER1,
          advertisingEnum.ADV_HOME_BANNER2
        )
        break
      case 3: // 酒慕模式
        startRendering(
          advertisingEnum.ADV_HOME_LIST2,
          advertisingEnum.ADV_HOME_BANNER1,
          advertisingEnum.ADV_HOME_BANNER2
        )
        break
      case 4: // 鑫复来模式
        startRendering(
          advertisingEnum.XFL_XXHD,
          advertisingEnum.ADV_HOME_BANNER1,
          advertisingEnum.ADV_HOME_BANNER2
        )
        break
      case 6: // 长来科技模式
        startRendering(
          advertisingEnum.CLKJ_XXHD,
          advertisingEnum.CLKJ_BANNER1,
          advertisingEnum.CLKJ_BANNER1
        )
        break
      default:
        break
    }
  } else {
    hyType.value = { name: '黑银', id: 0 }
    startRendering(
      advertisingEnum.ADV_HOME_LIST2,
      advertisingEnum.ADV_HOME_BANNER1,
      advertisingEnum.ADV_HOME_BANNER2
    )
  }
}

// 页面初次
onShow(async () => {
  changeMode()
})
onLoad(() => {
  shareCode.value = getQueryVariable('shareCode')
})

onReady(async () => {
  console.log('查看模式呢==》', hyType.value)
  shareCode.value = getQueryVariable('shareCode')
  // 渲染页面
  changeMode()
  // 黑豆商品
  getHeidouProductList()
  // 查询黑豆余额
  getMoney()
})

onReachBottom(() => {
  status.value = 'loading'
  getHeidouProductList()
})

onShareAppMessage((_res) => {
  const sourceTime = new Date().getTime()
  return {
    title: '黑银生活',
    path: sharePathFormat({ sourceTime })
  }
})

onPullDownRefresh(() => {
  setTimeout(async () => {
    getHeidouProductList()
    uni.stopPullDownRefresh()
  }, 1000)
})
</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';

.index-page {
  font-style: normal;
  text-align: center;
  min-height: 100vh;
  background-color: #f6f6f6;
  padding: 0 20rpx;
}

.section {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;
}

.tit {
  text-align: left;
  font-weight: bold;
}

.actions {
  margin-top: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;

  .item {
    width: 20%;
    margin-bottom: 20rpx;

    .icon {
      width: 100rpx;
      height: 100rpx;
    }
  }
}

.swiper {
  height: 110px;
  margin-top: 20rpx;

  .item {
    width: 100%;
    height: 100%;
  }
}

.hdBar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .link {
    display: flex;
    align-items: center;

    .name {
      font-weight: 600;
      font-size: 30rpx;
      margin-left: 10rpx;
    }

    .hy-icon-arrow-right {
      margin-left: 10rpx;
      font-size: 26rpx;
      font-weight: bold;
    }
  }

  .rest {
    font-size: 26rpx;
    color: $uni-text-color-light;
    font-weight: 600;

    .num {
      font-weight: 600;
      font-size: 30rpx;
      color: $uni-text-color;
    }
  }
}

.container {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  padding: 30rpx;
  gap: 20rpx;

  .itemWrap {
    width: calc((100% - 40rpx) / 3);
    border-radius: $section-raduis;
    background: $uni-bg-color-white;
    margin-bottom: $uni-spacing-col-lg;
    overflow: hidden;

    .contentBox {
      .imgCover {
        position: relative;
        width: 100%;
        flex-shrink: 0;
        margin-right: 20rpx;

        .img {
          width: 100%;
          // height: 200rpx;
          border-radius: $section-raduis;
        }
      }

      .content {
        padding: $uni-spacing-row-lg;
        text-align: left;

        .name {
          @include ellipsis;
          font-size: 28rpx;
        }

        .money {
          color: red;
          font-size: 26rpx;
          margin-top: 10rpx;
        }
      }
    }
  }
}

.rec {
  font-size: 30rpx;
  font-weight: bold;
  text-align: left;
  margin-bottom: 26rpx;
  margin-left: 20rpx;
}
</style>
